import { useEffect, useState } from 'react'

import { ThreadItem } from '@/app/types/Chat'
import { createClient } from '@/utils/supabase/client'

import Thread from './Thread'

const supabase = createClient()

export default function ThreadList() {
  const [threads, setThreads] = useState<ThreadItem[]>([])

  useEffect(() => {
    const getThreads = async () => {
      const { data, error } = await supabase
        .from('threads')
        .select('*')
        .order('created_at', { ascending: false })

      if (error) {
        console.error(error)
      }
      console.log('threads', data)
      setThreads(data || [])
    }
    getThreads()
  }, [])

  return (
    <div>
      {threads.map(thread => (
        <Thread key={thread.id} thread={thread} />
      ))}
    </div>
  )
}
